package hello

import (
	"appengine"
	"net/http"
)

func actionRoot(c *appengine.Context, w http.ResponseWriter, r *http.Request, params Params) (tmpl string) {
	tmpl = "index.html"
	recipes := listRandomRecipes(c, 6)
	fillRecipesWithIngredients(c, recipes, 4)
	params["recipes"] = recipes
	return
}

func actionRecipes(c *appengine.Context, w http.ResponseWriter, r *http.Request, params Params) (tmpl string) {
	categoryCode := r.FormValue("code")
	var recipes []*Recipe
	if len(categoryCode) == 0 {
		recipes = listAllRecipes(c, true)
		println("Recipes:", len(recipes))
	} else {
		category := getCategoryByCode(c, categoryCode)
		recipes = listRecipesByCategory(c, category.Id)
		params["category"] = category
	}
	fillRecipesWithIngredients(c, recipes, 5)
	params["recipes"] = recipes
	tmpl = "recipes.html"
	return
}

func actionAddRecipeComment(c *appengine.Context, w http.ResponseWriter, r *http.Request, params Params) (tmpl string) {
	comment := &RecipeComment{Text: r.FormValue("text"), Author: r.FormValue("author")}
	recipeId := parseInt(r.FormValue("recipeId"))
	saveRecipeComment(c, recipeId, comment)
	recipe, err := getRecipe(c, recipeId)
	notFoundOrPanic(err, w, r)
	http.Redirect(w, r, "recipe?code="+recipe.Code, http.StatusFound)
	return ""
}

func actionRecipe(c *appengine.Context, w http.ResponseWriter, r *http.Request, params Params) (tmpl string) {
	recipe := getRecipeByCode(c, r.FormValue("code"))
	recipe.Ingredients = listAllIngredients(c, recipe.Id)
	params["comments"] = listAllComments(c, recipe.Id)
	params["recipe"] = recipe
	tmpl = "recipe.html"
	return
}

func fillRecipesWithIngredients(c *appengine.Context, recipes []*Recipe, count int) {
	for i := 0; i < len(recipes); i++ {
		recipe := recipes[i]
		recipe.Ingredients = listIngredients(c, recipe.Id, count)
		if len(recipe.Ingredients) == count {
			recipe.HasMoreIngredients = true
			// puts 4 ingredients for rendering
			recipe.Ingredients = recipe.Ingredients[:count-1]
		}
	}
}

func actionAddRecipeForm(c *appengine.Context, w http.ResponseWriter, r *http.Request, params Params) (tmpl string) {
	tmpl = "addRecipeForm.html"
	return
}